package edu.cmu.vlis.wassup.db;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.mybeans.dao.DAOException;
import org.mybeans.factory.BeanFactory;
import org.mybeans.factory.BeanFactoryException;
import org.mybeans.factory.BeanTable;
import org.mybeans.factory.MatchArg;
import org.mybeans.factory.RollbackException;
import org.mybeans.factory.Transaction;

import edu.cmu.vlis.wassup.databean.Event;
import edu.cmu.vlis.wassup.databean.EventTag;

public class EventTagDAO {
	
	private BeanFactory<EventTag> factory;
	
	private static void loadProperties(){
        Properties props = new Properties();
        try {
            props.load(new FileInputStream("src/properties"));
            System.getProperties().putAll(props);
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

	public EventTagDAO() throws DAOException {
		try {					
//			String jdbcDriverName 	= "com.mysql.jdbc.Driver";
//			String jdbcURL			= "jdbc:mysql:///wassup?user=root&password=mysql";
//
//			BeanTable.useJDBC(jdbcDriverName, jdbcURL);
			BeanTable.useJDBC("com.mysql.jdbc.Driver", System.getProperty("org.mybeans.factory.jdbcURL")+
					"?user="+System.getProperty("org.mybeans.factory.user")
					+"&password="+System.getProperty("org.mybeans.factory.password"));
			
			EventDAO eventDAO = new EventDAO();
			
	        BeanTable<EventTag> eventTagTable = BeanTable.getInstance(EventTag.class, "eventTag", eventDAO.getFactory());
	        
	        if (!eventTagTable.exists()) 
	        	eventTagTable.create("eventId", "tag");
	        
	        // Long running web apps need to clean up idle database connections.
	        // So we can tell each BeanTable to clean them up.  (You would only notice
	        // a problem after leaving your web app running for several hours.)
	        eventTagTable.setIdleConnectionCleanup(true);
	
	        // Get a BeanFactory which the actions will use to read and write rows of the "user" table
	        factory = eventTagTable.getFactory();
		} catch (BeanFactoryException e) {
			throw new DAOException(e);
		}		
	}	
	
	
	/** Insert a new tuple of announcement_interesting mappping into the beanTable
	 * Returns error message if creation fails.
	 * Otherwise return a null upon success.
	 * 
	 * @param announcement_id
	 * @param tags
	 * @throws RollbackException
	 */
	public void insert(Event eventId, String tag) throws DAOException 
	{
		try {
			factory.create(eventId, tag);
		} catch (RollbackException e) {
			//e.printStackTrace();
			throw new DAOException(e);
		}
	}

	/** Lookup whether a typical event exists in the table
	 * Return Not Found if the events information is missing
	 * Otherwise return detailed information about event of a user
	 * 
	 * @param event_id
	 * @return
	 * @throws RollbackException
	 */
	public EventTag lookup(Event eventId, String tag) {
		EventTag eventTag = null;		
		try {
			eventTag = factory.lookup(eventId, tag);
		} catch (RollbackException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return eventTag;
	}
	
	
	/** Delete a tuple with primary key as composing of Event and Tag
	 * return null if no tuple is affected
	 * 
	 * @param event_id
	 * @return
	 */
	public void delete(Event eventId, String tag) {
		EventTag eventTag = lookup(eventId, tag);
		
		if (eventTag != null) {
			try {
				if (!Transaction.isActive())	// If the former transaction does not end normally
					Transaction.begin();	// Begin a new transaction
				factory.delete(eventTag);
				Transaction.commit();
			} catch (RollbackException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * Get all the messages about a certain Event - getTuplesFromAnnouncement
	 * @param a
	 * @return
	 * @throws RollbackException
	 */
	public EventTag[] getEventTagsForEvent (Event event)  {
		EventTag[] eventTags=null;
		try {
			eventTags = factory.match(MatchArg.equals("eventId", event));
		} catch (RollbackException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return eventTags;		
	}
	
	/**
	 * Get all the messages about a certain tag - getAnnouncementFromTag
	 * @param a
	 * @return
	 * @throws RollbackException
	 */
	public Event[] getEventsWithTag(String tag) throws RollbackException {
		EventTag[] eventTags = null;
		Event[] events = null;
		eventTags = factory.match(MatchArg.equals("tag",tag));
		
		if (eventTags != null && eventTags.length > 0) {
			events = new Event[eventTags.length];
			
			for (int i = 0; i < eventTags.length; i++) {
				events[i] = eventTags[i].getEventId();			
			}		
		}
		
		return events;
	}
	
	/**
	 * Get all the tags a certain user is interested in 
	 * @param a
	 * @return
	 * @throws RollbackException
	 */
	public String[] getTagForEvent(Event event) {
		EventTag[] eventTags = null;
		String[] tags = null;
		try {
			eventTags = factory.match(MatchArg.equals("eventId", event));
		} catch (RollbackException e) {			
			e.printStackTrace();
		}
		
		if (eventTags != null && eventTags.length > 0) {
			tags = new String[eventTags.length];
			
			for (int i = 0; i < eventTags.length; i++) {
				tags[i] = eventTags[i].getTag();			
			}		
		}
		
		return tags;
	}
	
	public static void main(String[] args) {
		
		try {
			EventTagDAO eventTagDAO = new EventTagDAO();			
			EventDAO eventDAO = new EventDAO();
			
			Event[] events = eventDAO.getAll();
			
			String[] tags = eventTagDAO.getTagForEvent(events[0]);
			for (int i = 0; i < tags.length; i++) {
				String tag = tags[i];
				System.out.println(tag);
				System.out.println(" -- Lookup ---");
				EventTag eventTag = eventTagDAO.lookup(events[0], tag);
				System.out.println(eventTag);
			}
			
			System.exit(0);
			
		} catch (DAOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
